from vadmin.models import SaveFile, UserProfile, Post
from op_drf.serializers import CustomModelSerializer
from rest_framework import serializers
from loguru import logger
from op_drf.dj_utils import flow_code_manage, check_serial_num


class SaveFileSerializer(CustomModelSerializer):
    """
    文件管理 简单序列化器
    """

    file_url = serializers.CharField(source="file.url", read_only=True)

    class Meta:
        model = SaveFile
        # exclude = ("description",)
        fields = "__all__"


class ReadUserProfileSerializer(CustomModelSerializer):
    class Meta:
        model = UserProfile
        # fields = ['id', 'asset_name', 'asset_code', 'use_year',"life_year"]
        fields = "__all__"


class WriteUserProfileSerializer(CustomModelSerializer):
    """
    用户管理 创建/更新时的列化器
    """

    def create(self, validated_data):
        logger.debug("序列化前传入的数据%s".format(validated_data))
        # 自动生成用户名称
        username = flow_code_manage("sys_user_name")
        check_serial_num(serial_num=username, model=self.Meta.model, check_field_name="username")
        validated_data["username"] = username
        data = super().create(validated_data)
        logger.debug(self.initial_data.get("password", None))
        data.set_password(self.initial_data.get("password", None))
        data.save()
        return data

    class Meta:
        model = UserProfile
        exclude = (
            "password",
            "secret",
        )


class ReadPostSerializer(CustomModelSerializer):

    class Meta:
        model = Post
        exclude=["is_delete"]
        # fields = "__all__"


class CreatePostSerializer(CustomModelSerializer):
    """
    岗位管理 创建/更新时的列化器
    """

    def create(self, validated_data):
        logger.debug("序列化前传入的数据%s".format(validated_data))
        post_code = flow_code_manage("sys_post_code")
        check_serial_num(serial_num=post_code, model=self.Meta.model, check_field_name="postCode")
        validated_data["postCode"] = post_code
        # postSort
        post_sort = self.Meta.model.objects.all()
        if hasattr(Post, "is_delete"):
            post_sort = post_sort.filter(is_delete=False)
        validated_data["postSort"] = post_sort.count()+1 if post_sort else 1
        data = super().create(validated_data)

        return data

    class Meta:
        model = Post
        fields = "__all__"


class UpdatePostSerializer(CustomModelSerializer):
    """
    岗位管理 创建/更新时的列化器
    """

    def update(self, instance, validated_data):
        logger.debug("序列化前传入的数据%s".format(validated_data))

        data = super().update(instance, validated_data)

        return data

    class Meta:
        model = Post
        fields = "__all__"
